//路由鉴权：项目当中的路由能不能被访问的设置
import router from '@/router'
//进度条业务包
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
//获取用户相关的小仓库内部的token数据去判断用户是否登录成功
import useUserStore from './store/modules/user'
import useMessagesStore from './store/modules/messages'
import useWebSocketStore from './store/modules/wschat'
import setting from './setting'
import type { friend } from './api/messages/type'
//引入本地文件储存检查函数
import { checkDirectories } from '@/utils/createdir'
import { REMOVE_CHATTINGFRIEND, SET_CHATTINGFRIEND, SET_CONTACTSFRIEND } from '@/utils/friends'
import { reqUpdateUnRead } from './api/messages'

//取消进度条的加载效果
nprogress.configure({ showSpinner: false })
const useStore = useUserStore(pinia)
const messagesStore = useMessagesStore(pinia)
const webSocketStore = useWebSocketStore(pinia)

//全局前置守卫
router.beforeEach(async (to, _from, next) => {
    //进度条开始
    nprogress.start()
    //获取token判断用户是否登录
    if (useStore.token) {
        //登录成功，访问login，不能访问，指向首页
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            //登录成功并获取用户信息后访问其余路由
            if (useStore.userId !== -1) {
                if (to.path.startsWith('/chat/friend') && to.path !== '/chat') {
                    const match = to.path.match(/\/chat\/friend\/([^\/]+)/)
                    const friendId = parseInt(match![1])
                    messagesStore.chattingFriend = useStore.chatListFriends.find((item: friend) => {
                        return item.userId === friendId
                    })
                    if (!messagesStore.chattingFriend) {
                        messagesStore.chattingFriend = messagesStore.contactsFriend
                    }
                    SET_CHATTINGFRIEND(messagesStore.chattingFriend)
                    for (let i = 0; i < messagesStore.conversations.length; i++) {
                        const nowConversation = messagesStore.conversations[i]
                        if (
                            nowConversation.conversation_id !==
                            messagesStore.chattingFriend.conversation_id
                        ) {
                            continue
                        }
                        if (messagesStore.chattingFriend.userId === nowConversation.users[0]) {
                            nowConversation.unRead2 = 0
                            reqUpdateUnRead({
                                conversation_id: nowConversation.conversation_id,
                                unRead2: 0,
                            })
                        } else {
                            nowConversation.unRead1 = 0
                            reqUpdateUnRead({
                                conversation_id: nowConversation.conversation_id,
                                unRead1: 0,
                            })
                        }
                        break
                    }
                }
                if (to.path.startsWith('/contacts')) {
                    messagesStore.chattingFriend = undefined
                    REMOVE_CHATTINGFRIEND()
                    const match = to.path.match(/\/contacts\/friendship\/([^\/]+)/)
                    if (match) {
                        const friendId = parseInt(match[1])
                        messagesStore.contactsFriend = useStore.friends.find((item: friend) => {
                            return item.userId === friendId
                        })!
                        SET_CONTACTSFRIEND(messagesStore.contactsFriend)
                    }
                }
                next()
            }
            //登录成功但未获取用户信息访问其余路由
            if (useStore.userId === -1) {
                try {
                    //获取用户信息后再放行
                    await useStore.userInfo()
                    await messagesStore.getChatHistory()
                    //开启WebSocket连接
                    webSocketStore.connectWebSocket()
                    //检查是否存在本地储存文件夹
                    await checkDirectories(useStore.userId)
                    next({ ...to })
                } catch (error) {
                    //token过期，获取不到用户信息或者用户手动修改本地存储token
                    await useStore.userLogout()
                    next({ path: '/login' }) //query: { redirect: to.path }
                }
            }
        }
    } else {
        //用户未登录
        if (to.path === '/login' || to.path === '/register') {
            next()
        } else {
            next({ path: '/login' }) //query: { redirect: to.path }
        }
    }
})

//全局后置守卫
router.afterEach((to) => {
    //进度条结束
    nprogress.done()
    //修改任务栏标题
    document.title = `${setting.title} - ${to.meta.title}`
})
